package cn.yanjr.common.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import org.apache.log4j.Logger;

public class AppPropertiesUtil {
	private static Logger LOGGER = Logger.getLogger(AppPropertiesUtil.class);

	public static Properties readPropertiesFile(String fileName, Class<?> clazz) {
		InputStream inStream = readFromUsrDir(fileName);
		if (inStream == null) {
			inStream = readFromClassPath(fileName, clazz);
		}

		Properties prop = new Properties();

		try {
			if (inStream != null) {
				prop.load(inStream);
				inStream.close();
				LOGGER.info("## 加载配置" + fileName + "成功");
			} else {
				prop = null;
				LOGGER.error("## 加载配置文件" + fileName + "出错");
			}
		} catch (Exception arg4) {
			prop = null;
			LOGGER.error("## 加载配置文件失败");
		}

		return prop;
	}

	private static InputStream readFromUsrDir(String fileName) {
//		String filePath = System.getProperty("user.dir") + File.separator + fileName;
		FileInputStream inStream = null;

		ClassLoader classLoader = AppPropertiesUtil.class.getClassLoader();
		URL resource = classLoader.getResource(fileName);
		String filePath = resource.getPath();
		try {
			inStream = new FileInputStream(filePath);
		} catch (FileNotFoundException arg3) {
			;
		}

		return inStream;
	}

	private static InputStream readFromClassPath(String fileName, Class<?> clazz) {
		return clazz.getClassLoader().getResourceAsStream(fileName);
	}

	public static void main(String[] args) throws Exception {
		ClassLoader classLoader = AppPropertiesUtil.class.getClassLoader();
		URL resource = classLoader.getResource("config.properties");
		String path = resource.getPath();
		System.out.println(path);
	}

}